package com.boarsoft.boar.sys.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.sys.SysRoleBiz;
import com.boarsoft.boar.sys.entity.SysRole;
import com.boarsoft.boar.sys.entity.SysUser;
import com.boarsoft.boar.sys.entity.UserRole;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("sysRoleBiz")
public class SysRoleBizImpl extends SimpleBizImpl implements SysRoleBiz {

	@Override
	@Transactional(readOnly = true)
	public PagedResult<SysRole> list(String userId, String key, int pageNo, int pageSize, String orderBy) {
		StringBuffer sb = new StringBuffer();
		sb.append("from ").append(SysRole.class.getName()).append(" r where 1=1");
		if (!SysUser.ADMIN_ID.equals(userId)) {
			sb.append(" and exists (select ur.id from ");
			sb.append(UserRole.class.getName());
			sb.append(" ur where ur.userId = '").append(userId).append("')");
		}
		// 模糊查询
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (r.name like '%").append(key);
			sb.append("%')");
		}
		sb.append(" group by r.id");
		String wql = sb.toString();
		int total = dao.getTotal("select count(r.id) ".concat(wql));
		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy).append(" desc");
		} else {
			sb.append(" order by r.name");
		}
		List<SysRole> alt = dao.list("select r ".concat(wql), pageNo, pageSize);
		return new PagedResult<SysRole>(total, alt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public boolean add(SysRole o) {
		dao.save(o);
		return true;
	}

	@Override
	@Transactional
	public boolean update(SysRole o) {
		return dao.update(o);
	}

	@Override
	@Transactional
	public void delete(String id) {
		SysRole o = (SysRole) dao.get(SysRole.class, id);
		o.getFuncs().clear();
		dao.delete(o);
	}

	@Override
	@Transactional(readOnly = true)
	public SysRole get(String id) {
		return (SysRole) dao.get(SysRole.class, id);
	}
}